<template>
  <div class="rightBodyContent">
    <div class="rightBodyContent-in" style="overflow-y: auto;overflow-x: auto;position: relative;">
      <div class="bg" :style="{backgroundImage:'url('+bgJpg+')',backgroundSize:'cover',backgroundPosition:'center'}"
           ref="boxCanvas">
        <div class="gobackBtn" @click="backlist">退出</div>
        <!--        奖品标题-->
        <div class="next title" v-if="awards.length>0">
          <span v-show="awards[currentAward].award">
            {{ detailOption ? detailOption.name : '--' }}
        </span
        >
        </div>
        <!--        中奖弹窗-->
        <div class="batch flexbox" v-show="!running && batchPlayers.length>0">
          <!--          @click="onKick(item)"-->
          <div class="player" v-for="(item, index) in batchPlayers" :key="index">
            {{ item.code }}
            <p class="player-txt">{{ item.prize.name }}</p>
          </div>
        </div>
        <div class="result" v-show="batchPlayers.length===0">
          <div @click="onKick(item, index)" class="lucky-dog" v-for="(item, index) in result[currentAward]"
               :key="index">
            {{ item.name }}
          </div>
        </div>
        <div class="content-box">
          <!--          左侧滚动-->
          <div id="myCanvasContainer" class="content-left">
            <canvas width="500" height="300" id="myCanvas" ref="canvas">
              <p>换个现代浏览器吧！</p>
            </canvas>
          </div>
          <!--          右侧按键-->
          <div class="content-right">
            <div class="showbox-in">
              <div class="showbox-in-title">{{ detailOption ? detailOption.name : '' }}</div>
              <div class="showbox-in-img">
                <div id="qrcode"></div>
              </div>
              <p>参与人扫码进入选号</p>
              <div class="showbox-in-number">
                <p class="showbox-in-number-list">盲号总数：<span>{{ detailOption ? detailOption.number : 0 }}</span></p>
                <p class="showbox-in-number-list">当前已选号码人数：
                  <count-to :startVal='startVal' :endVal='number' :duration='1000'></count-to>
                </p>
              </div>
              <div class="showbox-in-btn">
                <span @click="getStarFn">开盲</span>
              </div>
              <span @click="backlist">返回</span>
            </div>
          </div>
        </div>

        <!--        滚动的数据-->
        <div id="tags">
          <ul>
            <li v-for="(tag, index) in members" :key="index">
              <a href="javascript:;" target="_blank" style="height: auto;font-size: 60px;font-weight: bold;">
                {{ tag.name }}
              </a>
            </li>
          </ul>
        </div>
        <div class="buttons" style="display: none;">
          <el-select v-model="currentAward" size="small">
            <el-option v-for="(item, index) in awards"
                       :key="index"
                       :label="item.name"
                       :value="index"
            ></el-option>
          </el-select>
          <el-button size="small" ref="action" :disabled="buttonDisabled" type="danger" @click="toggle">
            {{ buttonText }}
          </el-button>
          <el-button size="small" @click="onNext" :disabled="goOn || running">下一轮</el-button>
          <el-button size="small"
                     :disabled="running"
                     type="warning"
                     class="el-icon-refresh"
                     @click="onReplay"
                     circle
          ></el-button>
          <span style="color: #000; margin-left:10px;">{{ players.length }}</span>
        </div>
      </div>
      <!--      进入弹窗-->
      <!--      <div class="showbox" v-if="dilogStatusFn">-->
      <!--        <div class="showbox-in">-->
      <!--          <div class="showbox-in-title">{{ detailOption ? detailOption.name : '' }}</div>-->
      <!--          <div class="showbox-in-img">-->
      <!--            <div id="qrcode"></div>-->
      <!--          </div>-->
      <!--          <p>参与人扫码进入选号</p>-->
      <!--          <div class="showbox-in-number">-->
      <!--            <p class="showbox-in-number-list">盲号总数：<span>{{ detailOption ? detailOption.number : 0 }}</span></p>-->
      <!--            <p class="showbox-in-number-list">当前已选号码人数：-->
      <!--              <count-to :startVal='startVal' :endVal='number' :duration='1000'></count-to>-->
      <!--            </p>-->
      <!--          </div>-->
      <!--          <div class="showbox-in-btn">-->
      <!--            <span @click="getStarFn">开盲</span>-->
      <!--          </div>-->
      <!--          <span @click="backlist">返回</span>-->
      <!--        </div>-->
      <!--      </div>-->
      <!--      生成随机数-->
      <div class="showbox" v-if="getNumber">
        <div class="showbox-in">
          <div class="showbox-in-number">
            <p class="showbox-in-number-list">盲号总数：<span>{{ detailOption ? detailOption.number : 0 }}</span></p>
          </div>
          <div class="showbox-in-btn">
            <span @click="getStarFn">生成随机号</span>
          </div>
          <span @click="backlist">返回</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import bgJpg from '@/assets/imageAdmin/bg.jpg'
import countTo from 'vue-count-to'
import QRCode from 'qrcodejs2'

export default {
  components: {
    countTo
  },
  data() {
    return {
      running: false,
      awards: [],
      currentAward: 0,
      result: [],
      players: [],
      batchPlayers: [],
      members: [],
      bgJpg: bgJpg,
      drawId: this.$route.query.id,
      number: 0,
      startVal: 0,
      timeNumberFn: null,
      isFullscreen: false,
      dilogStatusFn: true, //
      httpUrlInfo: '',
      getNumber: false
    }
  },
  watch: {
    currentAward: function () {
      this.batchPlayers = []
    }
  },
  computed: {
    buttonDisabled: function () {
      return (
          this.result[this.currentAward].length >=
          this.awards[this.currentAward].count || this.players.length === 0
      )
    },
    goOn: function () {
      return (
          this.result[this.currentAward].length <
          this.awards[this.currentAward].count &&
          this.result[this.currentAward].length > 0
      )
    },
    buttonText: function () {
      if (this.running) {
        return '停止'
      }
      if (this.goOn) {
        return '继续'
      }
      return '开始'
    }
  },
  methods: {
    // 请求抽奖数据
    getDrawInfo() {
      this.$fetch(this.api.giftDraw.edit, {id: this.$route.query.id}).then(res => {
        if (res.code === 0) {
          this.detailOption = res.detail
          let membersList = []
          let that = this
          for (let i = 0; i < res.detail.number; i++) {
            membersList.push({
              'name': (Number(i) + 1) < 10 ? ('0' + (Number(i) + 1)) + '号' : i + '号',
              'id': Number(i) + 1
            })
          }
          // members 参与者号码 [{"name": "01号", "id": 1}]
          this.members = this.copy(membersList)
          let canvas = this.$refs.canvas
          canvas.width = this.$refs.boxCanvas.offsetWidth
          canvas.height = document.body.offsetHeight - 170
          this.timeNumberFn = setInterval(() => {
            that.getNumberCode()
          }, 1000)
          this.$nextTick(function () {
            this.init()
          })
          // document.body.addEventListener('keyup', this.onKeyup) // 空格建
          this.qrcode()
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      })
    },
    InitFn() {
      this.$fetch(this.api.system_setting, {}).then(res => {
        if (!res.code) {
          console.log(res)
          this.httpUrlInfo = res.vo.url;
        } else {

        }
      })
    },
    // 生成二维码
    qrcode() {
      let qrcode = new QRCode('qrcode', {
        width: 200,
        height: 200, // 高度
        text: this.httpUrlInfo + '/school/#/drawlist?id=' + this.$route.query.id// 二维码内容
      })
      console.log(qrcode)
    },
    // 开始抽奖
    getStarFn() {
      let that = this
      if (this.number < this.detailOption.number) {
        this.$confirm('已选人数与抽签个数不符，是否确定开始抽签?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          clearInterval(that.timeNumberFn)
          that.gottoDrawFn()
        }).catch(() => {
        });
      }
    },
    gottoDrawFn() {
      let that = this
      this.dilogStatusFn = false
      this.start()
      // 抽签最后结果
      this.$fetch(this.api.giftDraw.end, {id: this.$route.query.id}).then(res => {
        if (res.code === 0) {
          let list_ = []
          for (let i in res.list) {
            res.list[i].code = Number(res.list[i].code) < 10 ? ('0' + Number(res.list[i].code)) + '号' : res.list[i].code + '号'
            list_.push(res.list[i])
          }
          this.batchPlayers = this.copy(list_)
          setTimeout(() => {
            that.stop()
          }, 3000)
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      })
    },
    // 点击抽奖
    toggle: function () {
      if (this.running) {
        this.stop()
      } else {
        this.start()
      }
    },
    getSpeed: function () {
      return [0.1 * Math.random() + 0.01, -(0.1 * Math.random() + 0.01)]
    },
    start: function () {
      this.running = true
      TagCanvas.SetSpeed('myCanvas', [5, 1])
    },
    stop: function () {
      this.running = false
      TagCanvas.SetSpeed('myCanvas', this.getSpeed())
      // let list_ = []
      // for (let i = 0; i < 17; i++) {
      //   list_.push(this.members[i])
      // }
      // this.batchPlayers = this.copy(list_)
      TagCanvas.Reload('myCanvas')
    },
    onNext: function () {
      this.batchPlayers = []
      if (this.currentAward < this.awards.length - 1) {
        this.currentAward += 1
      }
    },
    getRandomInt: function (min, max) {
      min = Math.ceil(min)
      max = Math.floor(max)
      return Math.floor(Math.random() * (max - min + 1)) + min
    },
    init: function () {
      try {
        TagCanvas.Start('myCanvas', 'tags', {
          textColour: "#fff",
          dragControl: 1,
          decel: 0.95,
          textHeight: 40,
          minSpeed: 0.02,
          maxSpeed: 0.4,
          outlineThickness: 0,
          depath: 2,
          initial: [
            0.1 * Math.random() + 0.01,
            -(0.1 * Math.random() + 0.01)
          ] // 配置旋转速度
        })
      } catch (e) {
        // something went wrong, hide the canvas container
        document.getElementById('myCanvasContainer').style.display =
            'none'
      }
    },
    onReplay: function () {
      var vm = this
      this.$confirm('重新抽奖会清空当前奖项的结果，无法撤销！', '确定要重新抽奖吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        vm.batchPlayers = []
        var p = vm.result.splice(vm.currentAward, 1, [])
        vm.players = vm.players.concat(p[0])
        localStorage.setItem('players', JSON.stringify(vm.players))
        localStorage.setItem('result', JSON.stringify(vm.result))
      })
    },
    onKeyup: function (e) {
      console.log(e)
      // 空格或回车键
      if (e.keyCode === 13 || e.keyCode === 32) {
        this.$refs.action.$el.click()
      }
    },
    copy: function (obj) {
      return JSON.parse(JSON.stringify(obj))
    },
    onKick: function (player) {
      var vm = this
      var index = vm.result[vm.currentAward].indexOf(player)
      this.$confirm('去掉后可继续抽一名', '去掉这名中奖者吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        if (vm.batchPlayers.indexOf(player) > -1) {
          vm.batchPlayers.splice(vm.batchPlayers.indexOf(player), 1)
        }
        vm.result[vm.currentAward].splice(index, 1)
        localStorage.setItem('result', JSON.stringify(vm.result))
      })
    },
    backlist() {
      this.$router.go(-1)
    },
    // 获取抽奖人选中号码数量
    getNumberCode() {
      if (this.number >= this.detailOption.number) {
        clearInterval(this.timeNumberFn)
      } else {
        this.prizeCodeFn()
      }
    },
    prizeCodeFn() {
      // draw_id 抽奖id status 1
      this.$fetch(this.api.giftDraw.prizeCode, {
        draw_id: this.$route.query.id,
        status: 1,
        loadingStatus: 1
      }).then(res => {
        if (res.code === 0) {
          this.startVal = JSON.parse(JSON.stringify(this.number))
          this.number = res.list.data.length
        } else {
        }
      })
    }
  },
  created() {
    // awards 奖品
    localStorage.setItem('awards', JSON.stringify([{'name': '二等奖', 'count': 3, 'award': 'Air pods'}, {
      'name': '一等奖',
      'count': 2,
      'award': 'HUAWEI Mate30Pro'
    }, {'name': '特等奖', 'count': 1, 'award': 'Apple MacPro'}]))
    this.awards = JSON.parse(localStorage.getItem('awards')) || []

    // [[{"name":"27号","id":27},{"name":"26号","id":26},{"name":"29号","id":29}],[],[]]
    var result = JSON.parse(localStorage.getItem('result')) || []
    for (var i = 0; i < this.awards.length; i++) {
      result[i] = result[i] || []
    }
    this.result = result

    this.choosed = JSON.parse(localStorage.getItem('choosed')) || {}
    console.log(this.choosed)

    var awards = this.awards || []
    this.rewards = awards.map(function (item, index) {
      return {
        level: index + 1,
        name: item.name,
        count: item.count,
        editing: {}
      }
    })
    this.getDrawInfo()
  },
  mounted: function () {
  },
  // 离开当前页面后执行
  destroyed: function () {
    clearInterval(this.timeNumberFn)
  }
}
</script>
<style scoped>

.bg {
  /*width: 100%;*/
  /*height: 100vh;*/
  position: relative;
}

a {
  color: #fff;
}

.buttons {
  position: absolute;
  bottom: 10px;
  width: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.next {
  font-size: 40px;
  color: #fff;
  line-height: 1.5;
  padding: 20px;
  text-align: center;
  position: absolute;
  width: 100%;
}

.next .title {
  color: yellow;
}

.el-select {
  width: 120px;
  margin-right: 10px;
}

.batch {
  position: absolute;
  width: 80%;
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  top: 50%;
  color: #fff;
  left: 50%;
  transform: translate(-50%, -50%);
  overflow-y: auto;
  height: 600px;
  background: rgba(0, 0, 0, .5);
  border-radius: 5px;
  box-shadow: 0 0 10px #333;
  padding: 10px;
}

.player-txt {
  font-size: 26px;
  color: #c70000;
}

.player {
  display: inline-block;
  text-align: center;
  font-size: 60px;
  width: 200px;
  background: #fff;
  line-height: 40px;
  color: #000;
  margin: 5px;
  border-radius: 10px;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.8);
  padding: 10px 0;
  height: 100px;
}

.lucky-dog {
  display: inline-block;
  font-size: 60px;
  text-align: center;
  width: 200px;
  background: #fff;
  line-height: 60px;
  color: #000;
  margin: 5px;
  border-radius: 10px;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.8);
  padding: 5px 0;
}

.result {
  width: 200px;
  position: absolute;
  right: 10px;
  top: 100px;
  color: #fff;
  line-height: 1.5;
  font-size: 60px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.showbox {
  position: absolute;
  height: 100%;
  width: 100%;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, .3);
  display: flex;
  justify-content: center;
  align-items: center;
}

.showbox-in {
  background: rgba(255, 255, 255, .9);
  border-radius: 10px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  width: 500px;
  height: 600px;
  box-shadow: 0 0 10px #ddd;
  font-size: 24px;
}

.showbox-in #qrcode {
  width: 216px;
  box-shadow: 0 4px 10px #999;
  border-radius: 5px;
  margin-bottom: 10px;
  border: 8px solid #fff;
}

.showbox-in-title {
  font-weight: bold;
  margin-bottom: 20px;
}

.showbox-in-btn {
  padding-top: 10px;
}

.showbox-in-btn span {
  background: #E6A23C;
  color: #fff;
  border-radius: 5px;
  padding: 14px 40px;
  cursor: pointer;
  box-shadow: 0 4px 10px #eca32e;
  display: block;
  margin-bottom: 20px;
}

.showbox-in-number {
  padding: 30px 0;
  font-weight: bold;
}

.showbox-in-number span {
  color: #ff0000;
  font-weight: bold;
  font-size: 28px;
}

.gobackBtn {
  position: absolute;
  top: 20px;
  left: 20px;
  color: #fff;
  font-size: 24px;
  font-weight: bold;
  z-index: 9999;
  cursor: pointer;
}
.content-box{
  display: flex;
}
.content-left{
  flex: 1;
}
.content-right{
  width: 500px;
}
</style>
